package com.hwtx.form.plugin;

import com.hwtx.form.annotation.*;
import com.hwtx.form.domain.def.Select;
import com.hwtx.form.domain.handle.FormDataHandle;
import com.hwtx.form.util.FormUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

@FormType(value = "dictInfo", comment = "字典相关处理")
@Slf4j
public class DictInfoDataHandle implements FormDataHandle {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Action(
            inputs = {
                    @Parameter(name = "parentId", comment = "字典编码")
            },
            outputs = {
                    @Parameter(name = "list", comment = "字典级联下拉数据")
            })
    @Log(type = OperationType.GET, value = "获取字典信息")
    public Map<String, Object> getDictInfoByCode(Map<String, Object> formData) {
        String code = FormUtil.getStrPostValue(formData, "code");
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        return jdbcTemplate.queryForMap("select label,code from sys_dict where code = ?", code);
    }

    @Log(type = OperationType.GET, value = "获取字典孩子节点信息")
    public List<Select.Option> dictChildrenInfo(Map<String, Object> formData) {
        String code = FormUtil.getStrPostValue(formData, "parentId");
        List<Map<String, Object>> ret;
        if (StringUtils.isEmpty(code)) {
            ret = jdbcTemplate.queryForList("select label,code from sys_dict where pid = 0");
        } else {
            ret = jdbcTemplate.queryForList("select label,code from sys_dict where pid in (select id from sys_dict where code = ?)", code);
        }
        return ret.stream().map(item -> {
            Select.Option option = new Select.Option();
            if (item.get("label") != null) {
                option.setLabel(item.get("label").toString());
            }
            if (item.get("code") != null) {
                option.setValue(item.get("code").toString());
            }
            return option;
        }).toList();
    }
}